import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'models/build_parameters.dart';
import 'services/config_service.dart';

class BuildParametersPage extends StatefulWidget {
  const BuildParametersPage({super.key});

  @override
  State<BuildParametersPage> createState() => _BuildParametersPageState();
}

class _BuildParametersPageState extends State<BuildParametersPage> {
  final _buildFormKey = GlobalKey<FormState>();
  late ConfigService _configService;
  BuildParameters _parameters = BuildParameters();
  bool _isLoading = true;

  // 控制器
  late TextEditingController _outputDirController;
  late TextEditingController _outputFilenameController;
  late TextEditingController _windowsIconController;
  late TextEditingController _pythonPathController;
  late TextEditingController _tempDirController;
  late TextEditingController _includePackagesController;
  late TextEditingController _excludePackagesController;

  @override
  void initState() {
    super.initState();
    _initializeControllers();
    _loadParameters();
  }

  void _initializeControllers() {
    _outputDirController = TextEditingController();
    _outputFilenameController = TextEditingController();
    _windowsIconController = TextEditingController();
    _pythonPathController = TextEditingController();
    _tempDirController = TextEditingController();
    _includePackagesController = TextEditingController();
    _excludePackagesController = TextEditingController();
  }

  Future<void> _loadParameters() async {
    _configService = await ConfigService.getInstance();
    // 这里可以扩展ConfigService来支持BuildParameters
    setState(() {
      _isLoading = false;
    });
    _updateControllers();
  }

  void _updateControllers() {
    _outputDirController.text = _parameters.outputDir;
    _outputFilenameController.text = _parameters.outputFilename;
    _windowsIconController.text = _parameters.windowsIconPath;
    _pythonPathController.text = _parameters.pythonPath;
    _tempDirController.text = _parameters.tempDir;
    _includePackagesController.text = _parameters.includePackages.join(', ');
    _excludePackagesController.text = _parameters.excludePackages.join(', ');
  }

  Future<void> _selectOutputDirectory() async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath(
      dialogTitle: '选择输出目录',
    );
    if (selectedDirectory != null) {
      _outputDirController.text = selectedDirectory;
    }
  }

  Future<void> _selectIconFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['ico', 'png'],
      dialogTitle: '选择应用图标',
    );
    if (result != null && result.files.single.path != null) {
      _windowsIconController.text = result.files.single.path!;
    }
  }

  Future<void> _selectPythonPath() async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath(
      dialogTitle: '选择Python路径',
    );
    if (selectedDirectory != null) {
      _pythonPathController.text = selectedDirectory;
    }
  }

  Future<void> _selectTempDirectory() async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath(
      dialogTitle: '选择临时目录',
    );
    if (selectedDirectory != null) {
      _tempDirController.text = selectedDirectory;
    }
  }

  void _saveParameters() {
    if (_buildFormKey.currentState!.validate()) {
      setState(() {
        _parameters = _parameters.copyWith(
          outputDir: _outputDirController.text,
          outputFilename: _outputFilenameController.text,
          windowsIconPath: _windowsIconController.text,
          pythonPath: _pythonPathController.text,
          tempDir: _tempDirController.text,
          includePackages: _includePackagesController.text
              .split(',')
              .map((e) => e.trim())
              .where((e) => e.isNotEmpty)
              .toList(),
          excludePackages: _excludePackagesController.text
              .split(',')
              .map((e) => e.trim())
              .where((e) => e.isNotEmpty)
              .toList(),
        );
      });

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('构建参数已保存'), backgroundColor: Colors.green),
      );
    }
  }

  void _resetParameters() {
    setState(() {
      _parameters = BuildParameters();
    });
    _updateControllers();

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('构建参数已重置'), backgroundColor: Colors.orange),
    );
  }

  void _previewCommand() {
    final args = _parameters.generateCommandLineArgs('your_script.py');
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Nuitka命令预览'),
        content: SingleChildScrollView(
          child: SelectableText(
            args.join(' \\\n  '),
            style: const TextStyle(fontFamily: 'monospace'),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _outputDirController.dispose();
    _outputFilenameController.dispose();
    _windowsIconController.dispose();
    _pythonPathController.dispose();
    _tempDirController.dispose();
    _includePackagesController.dispose();
    _excludePackagesController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Form(
          key: _buildFormKey,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        '构建参数配置',
                        style: Theme.of(context).textTheme.headlineMedium
                            ?.copyWith(fontWeight: FontWeight.bold),
                      ),
                    ),
                    ElevatedButton.icon(
                      onPressed: _previewCommand,
                      icon: const Icon(Icons.preview),
                      label: const Text('预览命令'),
                    ),
                  ],
                ),
                const SizedBox(height: 24),

                // 基础参数卡片
                _buildBasicParametersCard(),
                const SizedBox(height: 16),

                // 优化参数卡片
                _buildOptimizationCard(),
                const SizedBox(height: 16),

                // 包含/排除参数卡片
                _buildIncludeExcludeCard(),
                const SizedBox(height: 16),

                // Windows特定参数卡片
                _buildWindowsSpecificCard(),
                const SizedBox(height: 16),

                // 调试参数卡片
                _buildDebuggingCard(),
                const SizedBox(height: 16),

                // 高级参数卡片
                _buildAdvancedCard(),
                const SizedBox(height: 24),

                // 操作按钮
                _buildActionButtons(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBasicParametersCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '基础参数',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // 构建模式
            Text('构建模式', style: Theme.of(context).textTheme.titleMedium),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: CheckboxListTile(
                    title: const Text('独立可执行文件'),
                    subtitle: const Text('--standalone'),
                    value: _parameters.standalone,
                    onChanged: (value) {
                      setState(() {
                        _parameters = _parameters.copyWith(
                          standalone: value,
                          module: false,
                          plugin: false,
                        );
                      });
                    },
                  ),
                ),
                Expanded(
                  child: CheckboxListTile(
                    title: const Text('模块'),
                    subtitle: const Text('--module'),
                    value: _parameters.module,
                    onChanged: (value) {
                      setState(() {
                        _parameters = _parameters.copyWith(
                          module: value,
                          standalone: false,
                          plugin: false,
                        );
                      });
                    },
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // 输出目录
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _outputDirController,
                    decoration: const InputDecoration(
                      labelText: '输出目录',
                      hintText: '选择输出目录',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: _selectOutputDirectory,
                  icon: const Icon(Icons.folder_open),
                  label: const Text('浏览'),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // 输出文件名
            TextFormField(
              controller: _outputFilenameController,
              decoration: const InputDecoration(
                labelText: '输出文件名',
                hintText: '自定义输出文件名（可选）',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOptimizationCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '优化参数',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            SwitchListTile(
              title: const Text('启用优化'),
              subtitle: const Text('--enable-optimizations'),
              value: _parameters.enableOptimizations,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(
                    enableOptimizations: value,
                  );
                });
              },
            ),
            SwitchListTile(
              title: const Text('禁用断言'),
              subtitle: const Text('--no-asserts'),
              value: _parameters.noAsserts,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(noAsserts: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('禁用文档字符串'),
              subtitle: const Text('--no-docstrings'),
              value: _parameters.noDocstrings,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(noDocstrings: value);
                });
              },
            ),

            const SizedBox(height: 16),
            Text('优化级别', style: Theme.of(context).textTheme.titleMedium),
            const SizedBox(height: 8),
            DropdownButtonFormField<String>(
              value: _parameters.optimizationLevel,
              decoration: const InputDecoration(border: OutlineInputBorder()),
              items: const [
                DropdownMenuItem(value: 'O0', child: Text('O0 - 无优化')),
                DropdownMenuItem(value: 'O1', child: Text('O1 - 基础优化')),
                DropdownMenuItem(value: 'O2', child: Text('O2 - 高级优化')),
              ],
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(optimizationLevel: value);
                });
              },
            ),

            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: Text(
                    '并行任务数: ${_parameters.jobs == 0 ? "自动" : _parameters.jobs}',
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                ),
                Expanded(
                  child: Slider(
                    value: _parameters.jobs.toDouble(),
                    min: 0,
                    max: 16,
                    divisions: 16,
                    label: _parameters.jobs == 0
                        ? "自动"
                        : _parameters.jobs.toString(),
                    onChanged: (value) {
                      setState(() {
                        _parameters = _parameters.copyWith(jobs: value.toInt());
                      });
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildIncludeExcludeCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '包含/排除设置',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            TextFormField(
              controller: _includePackagesController,
              decoration: const InputDecoration(
                labelText: '包含的包',
                hintText: '用逗号分隔，如: numpy, pandas, requests',
                border: OutlineInputBorder(),
                helperText: '--include-package',
              ),
              maxLines: 2,
            ),
            const SizedBox(height: 16),

            TextFormField(
              controller: _excludePackagesController,
              decoration: const InputDecoration(
                labelText: '排除的包',
                hintText: '用逗号分隔，如: test, unittest, pytest',
                border: OutlineInputBorder(),
                helperText: '--nofollow-import-to',
              ),
              maxLines: 2,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildWindowsSpecificCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Windows特定参数',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            SwitchListTile(
              title: const Text('禁用控制台窗口'),
              subtitle: const Text('--windows-disable-console'),
              value: _parameters.windowsDisableConsole,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(
                    windowsDisableConsole: value,
                  );
                });
              },
            ),
            SwitchListTile(
              title: const Text('需要管理员权限'),
              subtitle: const Text('--windows-uac-admin'),
              value: _parameters.windowsUacAdmin,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(windowsUacAdmin: value);
                });
              },
            ),

            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _windowsIconController,
                    decoration: const InputDecoration(
                      labelText: 'Windows图标',
                      hintText: '选择.ico文件',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: _selectIconFile,
                  icon: const Icon(Icons.image),
                  label: const Text('浏览'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDebuggingCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '调试和信息参数',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            SwitchListTile(
              title: const Text('详细输出'),
              subtitle: const Text('--verbose'),
              value: _parameters.verbose,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(verbose: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('显示进度'),
              subtitle: const Text('--show-progress'),
              value: _parameters.showProgress,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(showProgress: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('显示内存使用'),
              subtitle: const Text('--show-memory'),
              value: _parameters.showMemory,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(showMemory: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('调试模式'),
              subtitle: const Text('--debug'),
              value: _parameters.debugMode,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(debugMode: value);
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAdvancedCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '高级参数',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            SwitchListTile(
              title: const Text('跟踪导入'),
              subtitle: const Text('--follow-imports'),
              value: _parameters.followImports,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(followImports: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('启用插件'),
              subtitle: const Text('--plugin-enable=all'),
              value: _parameters.enablePlugins,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(enablePlugins: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('链接时优化 (LTO)'),
              subtitle: const Text('--lto=yes'),
              value: _parameters.lto,
              onChanged: (value) {
                setState(() {
                  _parameters = _parameters.copyWith(lto: value);
                });
              },
            ),

            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _pythonPathController,
                    decoration: const InputDecoration(
                      labelText: 'Python路径',
                      hintText: '自定义Python路径（可选）',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: _selectPythonPath,
                  icon: const Icon(Icons.folder_open),
                  label: const Text('浏览'),
                ),
              ],
            ),
            const SizedBox(height: 16),

            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _tempDirController,
                    decoration: const InputDecoration(
                      labelText: '临时目录',
                      hintText: '自定义临时目录（可选）',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: _selectTempDirectory,
                  icon: const Icon(Icons.folder_open),
                  label: const Text('浏览'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildActionButtons() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        OutlinedButton.icon(
          onPressed: _resetParameters,
          icon: const Icon(Icons.refresh),
          label: const Text('重置参数'),
        ),
        const SizedBox(width: 16),
        ElevatedButton.icon(
          onPressed: _saveParameters,
          icon: const Icon(Icons.save),
          label: const Text('保存参数'),
        ),
      ],
    );
  }
}
